<template>
  <div class="class-detail">
    <a-spin :spinning="loading">
      <div v-if="classData" class="header">
        <h2 class="detail-title">班级详情</h2>
        <a-button type="primary" @click="openAddStudentModal">
          <template #icon><plus-outlined /></template>
          新增学员
      </a-button>
      </div>

      <!-- 班级基本信息区，改为文本行显示 -->
      <div class="basic-info-section">
        <div class="info-line">
          <span class="info-label">班级名称：</span>
          <span class="info-value">{{ classData?.className || '-' }}</span>
        </div>
        <div class="info-line">
          <span class="info-label">班级ID：</span>
          <span class="info-value">{{ classData?.classId || '-' }}</span>
        </div>
        <div class="info-line">
          <span class="info-label">班级时间：</span>
          <span class="info-value">{{ formatDate(classData?.startAt) }} - {{ formatDate(classData?.expireAt) }}</span>
        </div>
        <div class="info-line">
          <span class="info-label">班级人数：</span>
          <span class="info-value">{{ classData?.studentCount || 0 }}人</span>
        </div>
    </div>

      <!-- 打卡数据统计卡片 -->
      <div class="checkin-stats-section">
        <a-row :gutter="16">
          <a-col :span="6">
            <a-card class="checkin-card">
              <template #title>总打卡数据</template>
              <div class="checkin-data">
                <div class="checkin-item">
                  <div class="checkin-label">日均打卡人数</div>
                  <div class="checkin-value">{{ checkinStats.total.avgDaily || 0 }}人</div>
                </div>
                <div class="checkin-item">
                  <div class="checkin-label">打卡率</div>
                  <div class="checkin-value">{{ checkinStats.total.rate || '0%' }}</div>
                </div>
              </div>
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card class="checkin-card">
              <template #title>本季度打卡数据</template>
              <div class="checkin-data">
                <div class="checkin-item">
                  <div class="checkin-label">日均打卡人数</div>
                  <div class="checkin-value">{{ checkinStats.quarter.avgDaily || 0 }}人</div>
                </div>
                <div class="checkin-item">
                  <div class="checkin-label">打卡率</div>
                  <div class="checkin-value">{{ checkinStats.quarter.rate || '0%' }}</div>
                </div>
              </div>
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card class="checkin-card">
              <template #title>当月打卡数据</template>
              <div class="checkin-data">
                <div class="checkin-item">
                  <div class="checkin-label">日均打卡人数</div>
                  <div class="checkin-value">{{ checkinStats.month.avgDaily || 0 }}人</div>
                </div>
                <div class="checkin-item">
                  <div class="checkin-label">打卡率</div>
                  <div class="checkin-value">{{ checkinStats.month.rate || '0%' }}</div>
                </div>
              </div>
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card class="checkin-card">
              <template #title>本周打卡数据</template>
              <div class="checkin-data">
                <div class="checkin-item">
                  <div class="checkin-label">日均打卡人数</div>
                  <div class="checkin-value">{{ checkinStats.week.avgDaily || 0 }}人</div>
                </div>
                <div class="checkin-item">
                  <div class="checkin-label">打卡率</div>
                  <div class="checkin-value">{{ checkinStats.week.rate || '0%' }}</div>
                </div>
              </div>
            </a-card>
          </a-col>
    </a-row>

        <!-- 总打卡数据柱状图 -->
        <div class="chart-container">
          <a-card class="chart-card">
            <template #title>总打卡数据统计</template>
            <div id="checkin-chart" class="chart"></div>
          </a-card>
        </div>
    </div>

      <!-- 学生列表 Tab -->
      <a-tabs v-if="classData">
      <a-tab-pane key="list" tab="学生列表">
          <a-table :columns="studentColumns" :data-source="classData.students" rowKey="id" :pagination="false">
            <template #bodyCell="{ column, record }">
              <template v-if="column.dataIndex === 'checkinRate'">
                <a-progress :percent="parseFloat(record.checkinRate)" size="small" :format="percent => record.checkinRate" />
              </template>
              <template v-else-if="column.dataIndex === 'lastCheckinAt'">
                {{ formatDateTime(record.lastCheckinAt) }}
              </template>
              <template v-else-if="column.dataIndex === 'joinAt'">
                {{ formatDate(record.joinAt) }}
              </template>
            </template>
          </a-table>
      </a-tab-pane>
        <a-tab-pane key="tasks" tab="任务详情">
          <a-table :columns="taskColumns" :data-source="taskList" rowKey="planId" :pagination="{ pageSize: 10 }">
            <template #bodyCell="{ column, record }">
              <template v-if="column.dataIndex === 'progress'">
                <a-progress :percent="record.progress" size="small" />
              </template>
              <template v-else-if="column.dataIndex === 'publishAt'">
                {{ formatDateTime(record.publishAt) }}
              </template>
              <template v-else-if="column.dataIndex === 'effectivePunchEndAt'">
                {{ formatDateTime(record.effectivePunchEndAt) }}
              </template>
              <template v-else-if="column.dataIndex.startsWith('subPlan')">
                <a-tag v-if="record[column.dataIndex] && record[column.dataIndex] !== '-'" color="blue">
                  {{ record[column.dataIndex] }}
                </a-tag>
                <a-tag v-else color="default" style="background-color: #f0f0f0; color: #999;">
                  -
                </a-tag>
              </template>
            </template>
          </a-table>
      </a-tab-pane>
    </a-tabs>
    </a-spin>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { message } from 'ant-design-vue';
import { Api } from '@/api';
import * as echarts from 'echarts';
import { PlusOutlined } from '@ant-design/icons-vue';
import { useFormModal } from '@/hooks/useModal/';

// 根据实际返回字段修改接口定义
const router = useRouter();
const route = useRoute();
const loading = ref(true);
const classData = ref<API.ClassEntity | null>(null);

// 打卡数据统计
const checkinStats = ref({
  total: { avgDaily: 0, rate: '0%' },
  quarter: { avgDaily: 0, rate: '0%' },
  month: { avgDaily: 0, rate: '0%' },
  week: { avgDaily: 0, rate: '0%' }
});

// 获取URL参数中的班级ID
const classId = computed(() => route.params.classId || route.query.classId as string);

// 格式化日期
const formatDate = (dateString: string | undefined) => {
  if (!dateString) return '-';
  const date = new Date(dateString);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

// 格式化日期时间
const formatDateTime = (dateString: string | undefined) => {
  if (!dateString) return '-';
  const date = new Date(dateString);
  return `${formatDate(dateString)} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};

// 获取班级状态文本
const getClassStatusText = (status: number | undefined) => {
  const statusMap: Record<number, string> = {
    0: '已停用',
    1: '活跃中',
    2: '已毕业'
  };
  if (status === undefined) return '未知';
  return statusMap[status] || '未知';
};

// 获取班级年级文本
const getGradeText = (grade: number | undefined) => {
  if (grade === undefined) return '未知';
  if (grade === 0) return '幼儿园';
  if (grade >= 1 && grade <= 6) return `小学${grade}年级`;
  if (grade >= 7 && grade <= 8) return `初中${grade - 6}年级`;
  return '未知';
};

// 返回上一页
const goBack = () => {
  router.back();
};

// 学生列表列定义
const studentColumns = [
  { title: '学生ID', dataIndex: 'studentId', width: 120 },
  { title: '姓名', dataIndex: 'userName', width: 100 },
  { title: '手机号', dataIndex: 'phone', width: 120 },
  { title: '加入时间', dataIndex: 'joinAt', width: 120 },
  { title: '打卡天数', dataIndex: 'checkinDays', width: 100 },
  { title: '最后打卡', dataIndex: 'lastCheckinAt', width: 150 },
  { title: '打卡率', dataIndex: 'checkinRate', width: 150 }
];

// 任务列表数据
const taskList = ref<API.MainPlanDto[]>([]);

// 获取班级任务列表
const fetchTaskList = async () => {
  if (!classId.value) return;
  
  try {
    // 调用API获取所有主计划
    const response = await Api.studyPlan.getAllMainPlans();
    
    // 过滤出当前班级的计划
    if (classData.value) {
      const currentClassId = classData.value.classId;
      const filteredPlans = response.filter(plan => plan.classId === currentClassId) || [];
      
      // 处理子任务数据，将子任务拆分成单独的列
      taskList.value = filteredPlans.map(plan => {
        const result = { ...plan };
        
        // 为每个子任务创建单独的列
        for (let i = 0; i < 5; i++) {
          const subPlanKey = `subPlan${i+1}`;
          if (plan.subPlans && plan.subPlans[i]) {
            result[subPlanKey] = plan.subPlans[i].subPlanName;
          } else {
            result[subPlanKey] = '-';
          }
        }
        
        return result;
      });
    } else {
      taskList.value = [];
    }
    
    console.log('班级任务数据:', taskList.value);
  } catch (error) {
    console.error('获取班级任务数据失败:', error);
    message.error('获取班级任务数据失败');
  }
};

// 初始化打卡数据柱状图
const initCheckinChart = () => {
  const chartDom = document.getElementById('checkin-chart');
  if (!chartDom) return;
  
  const myChart = echarts.init(chartDom);
  
  // 处理打卡率字符串，提取数字部分
  const parseRateString = (rateStr: string) => {
    const match = rateStr.match(/(\d+)/);
    return match ? parseInt(match[1], 10) : 0;
  };
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['日均打卡人数', '打卡率(%)']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: ['总体', '本季度', '当月', '本周']
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '人数',
        min: 0,
        axisLabel: {
          formatter: '{value}人'
        }
      },
      {
        type: 'value',
        name: '百分比',
        min: 0,
        max: 100,
        axisLabel: {
          formatter: '{value}%'
        }
      }
    ],
    series: [
      {
        name: '日均打卡人数',
        type: 'bar',
        data: [
          checkinStats.value.total.avgDaily,
          checkinStats.value.quarter.avgDaily,
          checkinStats.value.month.avgDaily,
          checkinStats.value.week.avgDaily
        ]
      },
      {
        name: '打卡率(%)',
        type: 'bar',
        yAxisIndex: 1,
        data: [
          parseRateString(checkinStats.value.total.rate),
          parseRateString(checkinStats.value.quarter.rate),
          parseRateString(checkinStats.value.month.rate),
          parseRateString(checkinStats.value.week.rate)
        ]
      }
    ]
  };
  
  myChart.setOption(option);
  
  // 响应窗口大小变化
  window.addEventListener('resize', () => {
    myChart.resize();
  });
};

// 获取班级详情数据
const fetchClassDetail = async () => {
  // 打印路由信息，方便调试
  console.log('==================================================');
  console.log('路由信息:');
  console.log('route.params:', route.params);
  console.log('route.query:', route.query);
  console.log('route.fullPath:', route.fullPath);
  console.log('==================================================');
  
  if (!classId.value) {
    message.error('班级ID不能为空');
    // 如果URL中没有班级ID，显示错误消息但不立即返回
    console.error('班级ID为空，请检查跳转方式是否正确');
    
    // 可以在这里实现额外的错误恢复措施，比如尝试从localStorage获取最近浏览的班级ID
    const cachedClassId = localStorage.getItem('lastViewedClassId');
    if (cachedClassId) {
      console.log('从缓存中恢复班级ID:', cachedClassId);
      // 重定向到正确的URL
      router.replace(`/manage/class/${cachedClassId}`);
      return;
    }
    
    return;
  }
  
  // 存储当前访问的班级ID到localStorage，便于恢复
  localStorage.setItem('lastViewedClassId', classId.value);
  
  // 打印班级ID信息，使其更加醒目
  console.log('==================================================');
  console.log('请求班级详情数据');
  console.log('班级ID:', classId.value);
  console.log('ID类型:', typeof classId.value);
  console.log('==================================================');
  
  loading.value = true;
  try {
    // 使用API模块获取班级详情数据
    // 直接使用字符串形式的ID，不要尝试转换为数字
    const response = await Api.manageClass.classFindOne({ id: classId.value });
    
    classData.value = response;
    console.log('班级详情数据:', response);
  } catch (error) {
    console.error('获取班级详情失败:', error);
    message.error('获取班级详情失败');
  } finally {
    loading.value = false;
  }
};

// 获取班级打卡数据统计
const fetchCheckinStats = async () => {
  if (!classId.value) return;
  
  try {
    // 调用API获取打卡数据
    const response = await Api.manageClass.getClassAttendanceStatistics({ id: classId.value });
    
    // 更新打卡统计数据
    checkinStats.value = {
      total: { 
        avgDaily: response.total.dailyAverageCheckins, 
        rate: response.total.attendanceRate 
      },
      quarter: { 
        avgDaily: response.quarter.dailyAverageCheckins, 
        rate: response.quarter.attendanceRate 
      },
      month: { 
        avgDaily: response.month.dailyAverageCheckins, 
        rate: response.month.attendanceRate 
      },
      week: { 
        avgDaily: response.week.dailyAverageCheckins, 
        rate: response.week.attendanceRate 
      }
    };
    
    // 初始化图表
    setTimeout(() => {
      initCheckinChart();
    }, 300);
  } catch (error) {
    console.error('获取班级打卡数据失败:', error);
    message.error('获取班级打卡数据统计失败');
  }
};

// 监听整个路由对象的变化，确保所有场景下都能正确获取数据
watch(
  route,
  (newRoute) => {
    console.log('路由对象变化:', newRoute.fullPath);
    // 在路由发生变化且有班级ID时，重新获取数据
    if (classId.value) {
      fetchClassDetail();
      fetchCheckinStats();
      fetchTaskList();
    }
  },
  { deep: true, immediate: true } // 深度监听路由对象，并立即执行一次
);

// 页面加载时获取数据（保留原来的逻辑，以确保万无一失）
onMounted(() => {
  // 使用setTimeout延迟一下数据获取，确保在路由完全解析后获取数据
  setTimeout(() => {
    if (classId.value && !classData.value) {
      console.log('页面挂载后延迟获取数据，确保路由已完全解析');
      fetchClassDetail();
      fetchCheckinStats();
      fetchTaskList();
    }
  }, 100);
});

// 任务详情列定义
const taskColumns = [
  { title: '主任务ID', dataIndex: 'planId', width: 100 },
  { title: '主任务名', dataIndex: 'planName', width: 120 },
  { title: '子任务1', dataIndex: 'subPlan1', width: 100 },
  { title: '子任务2', dataIndex: 'subPlan2', width: 100 },
  { title: '子任务3', dataIndex: 'subPlan3', width: 100 },
  { title: '子任务4', dataIndex: 'subPlan4', width: 100 },
  { title: '子任务5', dataIndex: 'subPlan5', width: 100 },
  { title: '进度', dataIndex: 'progress', width: 80 },
  { title: '发布时间', dataIndex: 'publishAt', width: 120 },
  { title: '结束时间', dataIndex: 'effectivePunchEndAt', width: 120 }
];

// 保存符合条件的用户列表
const userOptions = ref<{ label: string; value: number; data: any }[]>([]);

// 获取符合条件的用户列表（线索用户、机会用户和体验用户）
const fetchUserOptions = async () => {
  try {
    // 获取用户列表数据
    const response = await Api.salesUser.userFindAll({
      page: 1,
      pageSize: 1000 // 获取足够多的数据以供筛选
    });
    
    if (response && response.items && Array.isArray(response.items)) {
      // 筛选出阶段为线索用户(1)、机会用户(2)和体验用户(6)的用户
      const filteredUsers = response.items.filter(user => 
        user.status === 1 || user.status === 2 || user.status === 6
      );
      
      // 格式化为下拉选项格式
      userOptions.value = filteredUsers.map(user => ({
        // 显示格式：用户姓名 (ID: xxx)
        label: `${user.userName || '未命名'} (ID: ${user.id})`,
        value: user.id,
        data: user // 保存完整用户数据供后续使用
      }));
      
      console.log('获取到符合条件的用户列表：', userOptions.value.length);
    }
  } catch (error) {
    console.error('获取用户列表失败：', error);
    message.error('获取用户列表失败');
  }
};

// 组件挂载时获取用户列表
onMounted(() => {
  fetchUserOptions();
});

// 表单弹窗
const [showModal] = useFormModal();

// 新增学员
const openAddStudentModal = async () => {
  // 如果打开模态框时还没有加载用户列表，重新获取
  if (userOptions.value.length === 0) {
    await fetchUserOptions();
  }

  const [formRef] = await showModal({
    modalProps: {
      title: '新增学生账号',
      width: 700,
      onFinish: async (values) => {
        try {
          // 1. 创建学员
          const studentResponse = await Api.manageStudent.studentCreate(values);
          
          // 如果是新建学生并且关联了用户ID，才更新用户阶段
          if (values.userId) {
            try {
              await Api.salesUser.userUpdate(
                { id: values.userId },
                { status: 3 } // 3是"已付费未激活"的值
              );
            } catch (error) {
              console.error('更新用户阶段失败:', error);
              message.error('学生创建成功，但更新用户阶段失败');
            }
          }
          
          // 2. 将学员加入当前班级
          if (studentResponse && studentResponse.id && classId.value) {
            try {
              // 获取班级详情，确保使用班级的数字ID而不是字符串ID
              const classIdNumber = classData.value?.id; // 使用班级的数字类型ID
              
              if (!classIdNumber) {
                throw new Error('无法获取有效的班级ID');
              }
              
              await Api.manageStudent.studentAddStudentToClass({
                studentId: studentResponse.id,
                classId: classIdNumber, // 使用班级对象的数字id，而非URL参数中的字符串classId
                joinAt: new Date().toISOString()
              });
              
              message.success('学员创建成功并已加入班级');
              
              // 3. 刷新班级详情数据
              fetchClassDetail();
            } catch (error) {
              console.error('将学员加入班级失败:', error);
              message.warning('学员创建成功，但加入班级失败');
            }
          } else {
            message.warning('学员创建成功，但加入班级失败');
          }
        } catch (error) {
          console.error('创建学员失败:', error);
          message.error('创建学员失败');
        }
      },
    },
    formProps: {
      labelWidth: 100,
      schemas: [
        {
          field: 'userName',
          component: 'Input',
          label: '学生姓名',
          colProps: {
            span: 12,
          },
          rules: [{ required: true, type: 'string' }],
        },
        {
          field: 'phone',
          component: 'Input',
          label: '手机号',
          colProps: {
            span: 12,
          },
          rules: [
            { required: true, type: 'string' },
            {
              validator: (rule, value, callback) => {
                if (value && !/^\d{11}$/.test(value)) {
                  callback('请输入正确的手机号');
                }
                callback();
              },
            },
          ],
        },
        {
          field: 'password',
          component: 'InputPassword',
          label: '密码',
          colProps: {
            span: 12,
          },
          componentProps: {
            placeholder: '请输入密码或留空生成随机密码',
          },
          rules: [{ required: true, type: 'string' }],
        },
        {
          field: 'userId',
          component: 'Select',
          label: '关联用户',
          colProps: {
            span: 12,
          },
          componentProps: {
            placeholder: '请选择用户',
            options: userOptions.value,
            showSearch: true,
            filterOption: (input, option) => {
              return (option?.label ?? '').toString().toLowerCase().includes(input.toLowerCase());
            },
            onChange: (value) => {
              if (value) {
                // 找到选中的用户完整数据
                const selectedUser = userOptions.value.find(item => item.value === value);
                if (selectedUser && selectedUser.data) {
                  // 更新表单字段
                  formRef?.setFieldsValue({
                    userName: selectedUser.data.nickname || selectedUser.data.userName || '',
                    phone: selectedUser.data.phone || '',
                    status: 1, // 学习中
                    studentType: 1, // 线上学习
                  });
                }
              }
            }
          },
          rules: [{ required: false, type: 'number' }],
        },
        {
          field: 'studentType',
          component: 'Select',
          label: '学习方式',
          colProps: {
            span: 12,
          },
          componentProps: {
            options: [
              { label: '线上学习', value: 1 },
              { label: '线下学习', value: 2 },
            ],
          },
          rules: [{ required: true, type: 'number' }],
        },
        {
          field: 'startAt',
          component: 'DatePicker',
          label: '开始时间',
          colProps: {
            span: 12,
          },
          componentProps: {
            style: {
              width: '100%',
            },
            showTime: true,
          },
          rules: [{ required: true, type: 'object' }],
        },
        {
          field: 'expireAt',
          component: 'DatePicker',
          label: '结束时间',
          colProps: {
            span: 12,
          },
          componentProps: {
            style: {
              width: '100%',
            },
            showTime: true,
          },
          rules: [{ required: true, type: 'object' }],
        },
        {
          field: 'status',
          component: 'Select',
          label: '状态',
          colProps: {
            span: 12,
          },
          componentProps: {
            options: [
              { label: '已停用', value: 0 },
              { label: '学习中', value: 1 },
              { label: '待续费', value: 2 },
              { label: '已毕业', value: 4 },
            ],
          },
          rules: [{ required: false, type: 'number' }],
        },
      ],
    },
  });

  // 设置默认值
  formRef?.setFieldsValue({
    studentType: 1, // 默认线上学习
    status: 1, // 默认学习中
    startAt: classData.value?.startAt ? new Date(classData.value.startAt) : new Date(), // 使用班级开班时间
    expireAt: classData.value?.expireAt ? new Date(classData.value.expireAt) : new Date(new Date().setFullYear(new Date().getFullYear() + 1)), // 使用班级结业时间
  });
};
</script>

<style scoped>
.class-detail { 
  background: #fff; 
  padding: 24px; 
  border-radius: 8px;
  min-height: 500px;
}
.header { 
  display: flex; 
  align-items: center; 
  justify-content: space-between;
  margin-bottom: 24px;
  flex-wrap: wrap;
}
.detail-title { 
  font-size: 24px; 
  font-weight: bold;
  margin-right: 24px;
  padding-bottom: 0;
  margin-bottom: 0;
}
.basic-info-section {
  margin: 24px 0;
  background-color: #f9f9f9;
  padding: 16px 24px;
  border-radius: 8px;
  border-left: 4px solid #1890ff;
}
.info-line {
  margin-bottom: 12px;
  line-height: 1.8;
}
.info-label {
  font-size: 16px;
  font-weight: bold;
  margin-right: 8px;
  color: #333;
  display: inline-block;
  min-width: 100px;
}
.info-value {
  font-size: 16px;
  color: #666;
}
/* 打卡数据统计样式 */
.checkin-stats-section {
  margin: 24px 0;
}
.checkin-card {
  height: 100%;
}
.checkin-data {
  padding: 8px 0;
}
.checkin-item {
  margin-bottom: 8px;
}
.checkin-label {
  font-size: 14px;
  color: #666;
}
.checkin-value {
  font-size: 18px;
  font-weight: bold;
  color: #1890ff;
}
.chart-container {
  margin-top: 16px;
}
.chart-card {
  width: 100%;
}
.chart {
  height: 300px;
  width: 100%;
}
.sub-plans-list {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}
/* 子任务列样式 */
:deep(.ant-table td[class*="subPlan"]) {
  color: #1890ff;
  font-weight: 500;
}
.empty-subplan {
  color: #d9d9d9;
  font-style: italic;
}
</style>